<script lang="ts" setup>
  import type { GameEnrollType } from '@/types/game';
  import {
    getGameEnrollTypes,
    deleteGameEnrollType,
    getPlayerIdsFromEnrollType,
    removePlayersFromEnrollType,
  } from '@/api/game';
  import { onMounted, ref, watch } from 'vue';
  import { Modal } from '@arco-design/web-vue';
  import type { User } from '@/types/user';
  import EnrollTypeAddPlayer from './enroll-type-add-player.vue';
  import EnrollTypeEditor from './enroll-type-editor.vue';

  const props = defineProps<{
    gameId: string;
  }>();

  const list = ref<GameEnrollType[]>([]);
  const userMap = ref<{
    [key: number]: User[];
  }>({});
  const initPlayerData = async () => {
    try {
      const res = await Promise.all(
        list.value.map((i) => {
          return getPlayerIdsFromEnrollType(props.gameId, i.id);
        })
      );
      const map: {
        [key: number]: User[];
      } = {};
      list.value.forEach((i, index) => {
        map[i.id] = res[index].data.data;
      });
      userMap.value = map;
    } finally {
      // do nothing
    }
  };

  watch([list], initPlayerData, {
    immediate: true,
  });

  const initData = async () => {
    const res = await getGameEnrollTypes(props.gameId);
    list.value = res.data.data;
  };

  onMounted(initData);

  const editorConfig = ref<{
    visible: boolean;
    record?: GameEnrollType;
  }>({
    visible: false,
  });
  const handleCreateDone = () => {
    editorConfig.value = {
      visible: false,
    };
    initData();
  };
  const tryToDelete = (item: GameEnrollType) => {
    Modal.confirm({
      title: '提示',
      content: '确定删除该组别？',
      onBeforeOk: async () => {
        await deleteGameEnrollType(item.id, item.gameId);
        initData();
      },
    });
  };

  const addingPlayer = ref(-1);
  const handleAddPlayerDone = (refresh: boolean) => {
    addingPlayer.value = -1;
    if (refresh) {
      initPlayerData();
    }
  };
  const handleRemovePlayer = async (user: User, type: GameEnrollType) => {
    await removePlayersFromEnrollType(props.gameId, type.id, [user.id]);
    initPlayerData();
  };
</script>

<template>
  <div>
    <div style="margin: 12px 0 20px">
      <a-button @click="editorConfig = { visible: true }">
        <template #icon><icon-plus /></template>
        添加组别
      </a-button>
    </div>
    <div>
      <a-collapse>
        <a-collapse-item
          v-for="type in list"
          :key="type.id"
          :header="type.name"
        >
          <template #extra>
            <a-space :size="12">
              <a-link @click.stop="addingPlayer = type.id">添加球员</a-link>
              <a-link
                @click.stop="editorConfig = { visible: true, record: type }"
              >
                修改
              </a-link>
              <a-link @click.stop="tryToDelete(type)">删除</a-link>
            </a-space>
          </template>

          <a-row :gutter="[12, 12]">
            <a-col
              v-for="user in userMap[type.id] || []"
              :key="user.id"
              :span="6"
            >
              <div class="user-info">
                <div class="user-img">
                  <img v-if="user.profile" :src="user.profile" />
                </div>
                <div class="user-right">
                  <div class="user-name">
                    {{ user.nickname }}
                  </div>
                  <div class="user-sub-info">
                    <a-space>
                      <span>{{ user.sex ? '男' : '女' }}</span>
                      <span>{{ user.ageType === 1 ? '青少年' : '成人' }}</span>
                    </a-space>
                  </div>
                  <div class="user-sub-info">
                    最佳杆数：{{ user.best || '-' }}
                  </div>
                </div>

                <a @click="handleRemovePlayer(user, type)">
                  <icon-close />
                </a>
              </div>
            </a-col>
          </a-row>
        </a-collapse-item>
      </a-collapse>
    </div>

    <EnrollTypeEditor
      v-if="editorConfig.visible"
      :game-id="gameId"
      :record="editorConfig.record"
      @close="handleCreateDone"
    />

    <EnrollTypeAddPlayer
      v-if="addingPlayer > 0"
      :game-id="gameId"
      :type-id="addingPlayer"
      @close="handleAddPlayerDone"
    />
  </div>
</template>

<style lang="less" scoped>
  .user-info {
    display: flex;
    position: relative;
    a {
      display: none;
      cursor: pointer;
      color: rgb(var(--red-6));
      position: absolute;
      right: 10px;
    }
    &:hover {
      a {
        display: block;
      }
    }
  }
  .user-img {
    width: 32px;
    height: 32px;
    background: rgb(var(--gray-2));
    border-radius: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 5px;
    overflow: hidden;
    img {
      max-width: 100%;
      max-height: 100%;
    }
  }
  .user-right {
    flex: 1;
    margin-left: 8px;
  }
  .user-name {
    font-weight: 600;
    line-height: 20px;
  }
  .user-sub-info {
    font-size: 12px;
    line-height: 20px;
    color: var(--color-text-2);
  }
</style>
